﻿// Copyright (c) 2014 Jonathan Magnan (http://jonathanmagnan.com/).
// All rights reserved (http://zzzproject.com/sqlbulkcopy-extensions/).
// Licensed under MIT License (MIT) (https://zsqlbulkcopy.codeplex.com/license/).

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Reflection;
#if NET40
using System.Runtime.Caching;
#endif
#if NET20
using Z.Net.Legacy20;
#elif NET35 || NET40
using System.Linq;
#endif

namespace Z.Net.Extensions
{
    internal partial class SqlBulkOperation
    {
        /// <summary>
        ///     Sets common setting.
        /// </summary>
        public void SetCommonSettingSingle()
        {
#if NET20
            MappingList = new List<SqlBulkCopyColumnMapping>(CollectionBaseExtensions.Cast<SqlBulkCopyColumnMapping>(SqlBulkCopy.ColumnMappings));
#elif NET35 || NET40
            MappingList = SqlBulkCopy.ColumnMappings.Cast<SqlBulkCopyColumnMapping>().ToList();
#endif

// ReSharper disable PossibleNullReferenceException
            Type type = SqlBulkCopy.GetType();
            SqlConnection = type.GetField("_connection", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(SqlBulkCopy) as SqlConnection;
            SqlTransaction = type.GetField("_externalTransaction", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(SqlBulkCopy) as SqlTransaction;
// ReSharper restore PossibleNullReferenceException

#if NET40
            string primaryKeyCache = Config.PrimaryKeys == null ? "" : string.Join(";", Config.PrimaryKeys);
            string cacheName = string.Format("Z.Net.Extensions.SqlBulkOperation.Setting;{0}_{1}_{2}_{3}", SqlConnection.DataSource, SqlConnection.Database, SqlBulkCopy.DestinationTableName, primaryKeyCache);
            MemoryCache memoryCache = MemoryCache.Default;
            if (Config.UseCache && memoryCache[cacheName] != null)
            {
                Setting = (SqlBulkOperationSetting) memoryCache[cacheName];
            }
            else
            {
#endif
                Setting = new SqlBulkOperationSetting();
                if (Config.PrimaryKeys != null)
                {
                    Setting.PrimaryKeys = new List<string>(Config.PrimaryKeys);
                }

                GetSqlInformation();
                GetSqlInformationSqlType();

#if NET40
                if (Config.UseCache)
                {
                    memoryCache.Add(cacheName, Setting, new CacheItemPolicy());
                }
            }
#endif
        }
    }
}